<?php
// +----------------------------------------------------------------------
// | 多客怪兽框架多平台开发框架 [ 以下开发工具自动生成-版权勿删 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~2024 http://www.dkyx.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 刘泓宾（514660094@qq.com）
// +----------------------------------------------------------------------

namespace addons\example\model;


/**
 * 用户管理模型文件
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 */
class ExampleUser extends ExampleBaseModel
{

    // 字段自动类型转换
    protected $type = array(
        'bot_ids' => 'json',
    );
    // 数据输出需要追加的属性
    protected $append = array(
        'bot_names',
        'expire_time_text'
    );
    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }


    /**
     * 增加修改全局查询范围属性函数
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $scope
     * @return $this
     */
    public function setGlobalScope($scope=['alias'])
    {
        $this->globalScope = $scope;
        return $this;
    }


    /**
     * 定义自定义默认全局查询范围
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $query \think\Model
     * @return void
     */
    public function scopeAlias($query)
    {
        if (get_plaid()) {
            $query->where([$this->alias . '.plaid' => get_plaid()]);
        }
        if (get_appid()) {
            $query->where([$this->alias . '.appid' => get_appid()]);
        }
    }

    /**
     * 关联ExampleIndustry模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function industry()
    {
        return $this->belongsTo(ExampleIndustry::class, 'industry_id', 'id');
    }
    /**
     * 生成远程下拉多选数据
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $val
     * @param $data
     * @return array
     */
    public function getBotNamesAttr($val, $data)
    {
        $tags = [];
        $res = ExampleBot::whereIn('id', json_decode($data['bot_ids'], true))->select();
        foreach ($res as $key => $value) {
            $tags[] = $value['name'];
        }
        return $tags;
    }

    public function getExpireTimeTextAttr($val, $data)
    {
        if ($data['expire_time'] < time()) {
            return '已过期';
        } else {
            return date('Y-m-d H:i:s', $data['expire_time']);
        }
    }

}
